import path from "path";
import Inspect from "vite-plugin-inspect";
import { defineConfig, loadEnv } from "vite";
import VueMacros from "unplugin-vue-macros/vite";
import UnoCSS from "unocss/vite";
import mkcert from "vite-plugin-mkcert";
import glob from "fast-glob";
import vueJsx from "@vitejs/plugin-vue-jsx";
import Components from "unplugin-vue-components/vite";
import {
  docPackage,
  ipPackage,
  getPackageDependencies,
  projRoot
} from "@ikun-plus/build-utils";
import { MarkdownTransform } from "./.vitepress/plugins/markdown-transform";

import type { Alias } from "vite";

const alias: Alias[] = [
  {
    find: "~/",
    replacement: `${path.resolve(__dirname, "./.vitepress")}/`
  }
];
if (process.env.DOC_ENV !== "production") {
  alias.push(
    {
      find: /^ikun-plus(\/(es|lib))?$/,
      replacement: path.resolve(projRoot, "packages/ikun-plus/index.ts")
    },
    {
      find: /^ikun-plus\/(es|lib)\/(.*)$/,
      replacement: `${path.resolve(projRoot, "packages")}/$2`
    }
  );
}

export default defineConfig(async ({ mode }) => {
  const env = loadEnv(mode, process.cwd(), "");

  const { dependencies: epDeps } = getPackageDependencies(ipPackage);
  const { dependencies: docsDeps } = getPackageDependencies(docPackage);

  const optimizeDeps = [...new Set([...epDeps, ...docsDeps])].filter(
    (dep) =>
      !dep.startsWith("@types/") &&
      !["@ikun-plus/metadata", "ikun-plus"].includes(dep)
  );

  optimizeDeps.push(
    ...(await glob(["dayjs/plugin/*.js"], {
      cwd: path.resolve(projRoot, "node_modules"),
      onlyFiles: true
    }))
  );

  return {
    server: {
      port: 8111,
      host: true,
      https: !!env.HTTPS,
      fs: {
        allow: [projRoot]
      }
    },
    resolve: {
      alias
    },
    plugins: [
      VueMacros({
        setupComponent: false,
        setupSFC: false,
        plugins: {
          vueJsx: vueJsx()
        }
      }),

      // https://github.com/antfu/unplugin-vue-components
      Components({
        dirs: [".vitepress/components"],

        allowOverrides: true,

        // custom resolvers
        resolvers: [],

        // allow auto import and register components used in markdown
        include: [/\.vue$/, /\.vue\?vue/, /\.md$/]
      }),
      UnoCSS(),
      MarkdownTransform(),
      Inspect(),
      mkcert()
    ],
    optimizeDeps: {
      include: optimizeDeps
    }
  } as any;
});
